<?php

namespace App\Http\Controllers\Guard\User;

use App\Exports\ChengBaoExport;
use App\Exports\CountPriceExport;
use App\Exports\LiPeiExport;
use App\Http\Controllers\Common\GuardController;
use App\Imports\ChengBaoImport;
use App\Models\Rbac\GuardUser;
use App\Models\Rbac\GuardUserPrice;
use App\Models\User\ChengBao;
use App\Models\User\ChengBaoSum;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class ChengBaoController extends GuardController {


    public function index(Request $request) {

        $token = $request->header('token');
        $id = checkJWT($token)['id'];

        $guardUser = GuardUser::where(compact('id'))->first();
        $conditions = $request->input();
        $records = (new ChengBao())->getLst($conditions);

        if($guardUser->name!='SuperAdmin'){
            $records = $records->where('account',$guardUser->id);
        }
        $records = $records->with('getGuardUser:id,name')
            ->paginate($conditions['pageSize'],['*'],'page',$conditions['page']);

        return responseSuccess($records->items(),$records->total());

    }

    public function del(Request $request) {
        $import_number = $request->input('ids',0);
        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        //$guardUser = GuardUser::where(compact($id))->first();
        try{
            DB::beginTransaction();

            ChengBao::where(compact('import_number'))->forceDelete();
            //ChengBaoSum::where(compact('import_number'))->forceDelete();
            $inst = ChengBaoSum::where(compact('import_number'))->first();
            //$inst->records_count = 0-$inst->records_count;
            //$inst->account = $id;
            //$inst->save();

            ChengBaoSum::create([
                'import_number'=>$import_number,
                'records_count'=> 0-$inst->records_count,
                'account'=>$id,
                'bao_sum_price'=>$inst->bao_sum_price,
                'service_price'=>$inst->service_price
            ]);

            DB::commit();
            return responseSuccess();
        }catch(\Exception $e){
            DB::rollback();
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            Log::error($tip);
            return responseSuccess();
        }



    }

    public function uploadChengBao(Request $request) {

        $token = $request->input('token');
        $id = checkJWT($token)['id'];
        $guardUser = GuardUser::where(compact('id'))->first();

        if(empty($guardUser)){
            return responseFail('当前用户无效！');
        }


        $file = $request->file('file');
        if(empty($file) || !$file->isValid()){
            return responseFail('文件无效！');
        }
        $path = $file->store('user','upload');
        $import = new ChengBaoImport($guardUser->id);
        Excel::import($import, storage_path('app/public/upload/'.$path));
        if($import->success){
            $count = $import->count;
            $baoSumPrice = $import->baoSumPrice;
            $servicePrice = $import->servicePrice;


            return responseSuccess(compact('count','baoSumPrice','servicePrice'),0,$import->msg);
            //return responseSuccess(compact('count','baoSumPrice','servicePrice'),0,$msg);
        }else{
            return responseFail($import->msg);
        }

    }

    public function sumIndex(Request $request) {
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',20);
        $conditions = $request->input();
        $records = (new ChengBaoSum())->getLst($conditions)

            ->whereHas('getGuardUser', function ($q) use ($conditions) {
                if(!empty($conditions['account'])){
                    $q->where('name','like','%'.$conditions['account'].'%');
                }
            })
            ->with('getGuardUser')->paginate($pageSize,$this->getCol,'page',$page);
        return responseSuccess($records->items(),$records->total());
    }

    public function exportFile(Request $request) {
        $conditions = $request->input();
        $conditions['orderBy']['col'] = 'created_at';
        $conditions['orderBy']['sort'] = 'desc';
        return Excel::download(new ChengBaoExport($conditions),'承保清单.xlsx');

    }

    public function countPriceIndex(Request $request) {

        $conditions = $request->input();

        $conditions['orderBy']['col'] = 'date';
        $conditions['orderBy']['sort'] = 'desc';

        $date = $request->input('date',[date('Y-m-d'),date('Y-m-d')]);
        $records = (new GuardUserPrice())->getLst($conditions)->with('getGuardUser')->paginate($conditions['pageSize'],['*'],'page',$conditions['page']);

        $sum_day_car_count = GuardUserPrice::whereBetween('date',$date)->sum('day_car_count');
        $sum_day_bao_price = GuardUserPrice::whereBetween('date',$date)->sum('day_bao_price');
        $sum_day_service_price = GuardUserPrice::whereBetween('date',$date)->sum('day_service_price');

        $sum_ins_car_count = 0;
        $sum_ins_bao_price = 0;
        $sum_ins_service_price = 0;

        $sum_full_price = 0;

        $guardUsers = GuardUser::get();

        foreach ($guardUsers as $guardUser) {

            $temp =  GuardUserPrice::where('account',$guardUser->id)->where('date',$date[1])->first();

            if(!empty($temp)){
                $sum_ins_car_count += $temp->ins_car_count;
                $sum_ins_bao_price += $temp->ins_bao_price;
                $sum_ins_service_price += $temp->ins_service_price;
                $sum_full_price += $temp->full_price;
            }
        }

        $msg = "合计：当日服务车辆 $sum_day_car_count ，当日服务保费 $sum_day_bao_price ，当日服务费 $sum_day_service_price ，累计服务车辆 $sum_ins_car_count ，累计保费 $sum_ins_bao_price ，累计服务费 $sum_ins_service_price ，已满期利润额 $sum_full_price";


        return responseSuccess($records->items(),$records->total(),$msg,compact('sum_day_car_count', 'sum_day_bao_price',
            'sum_day_service_price','sum_ins_car_count','sum_ins_bao_price','sum_ins_service_price'));

    }

    public function exportCountPrice(Request $request) {
        $conditions = $request->input();
        return Excel::download(new CountPriceExport($conditions),'保驾优赔数据统计表.xlsx');
    }

    public function handleCountPrice(Request $request) {
        $date = $request->input('date',date('Y-m-d'));

        Artisan::call('count:price',['date'=>$date]);

        return responseSuccess();


    }

}
